<?php
/**
 * Created by PhpStorm.
 * User: Dean.Wu
 * Date: 2018/2/24 0024
 * Time: 15:18
 */
namespace App\Http\Controllers\Admin;

use App\Models\AdminPermission;
use App\Models\AdminRole;

class RoleController extends Controller{
    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @name 角色列表
     * @author wudean
     */
    public function index()
    {
        $roles = AdminRole::paginate(10);
        return view('admin.role.index', compact('roles'));
    }

    /**
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @name 创建角色
     */
    public function create()
    {
        return view('admin.role.create');
    }

    /**
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     * @name 存储角色
     */
    public function store()
    {
        $this->validate(request(), [
            'name' => 'required|min:3',
            'description' => 'required',
        ]);

        AdminRole::create(request(['name', 'description']));
        return redirect('admin/roles');
    }


    /**
     * @param AdminRole $role
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @name 角色权限列表
     */
    public function permission(AdminRole $role)
    {
        $permissions = AdminPermission::all();
        $myPermissions = $role->permissions;
        return view('admin.role.permission', compact('permissions', 'myPermissions', 'role'));
    }

    /**
     * @param AdminRole $role
     * @return \Illuminate\Http\RedirectResponse
     * @name 保存角色权限
     */
    public function storePermission(AdminRole $role)
    {
        $this->validate(request(),[
            'permissions' => 'required|array'
        ]);

        $permissions = AdminPermission::find(request('permissions'));
        $myPermissions = $role->permissions;

        // 对已经有的权限
        $addPermissions = $permissions->diff($myPermissions);
        foreach ($addPermissions as $permission) {
            $role->grantPermission($permission);
        }

        $deletePermissions = $myPermissions->diff($permissions);
        foreach ($deletePermissions as $permission) {
            $role->deletePermission($permission);
        }
        return back();
    }
}